package com.snail.study.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 网络传输数据（非阻塞时IO）
 * @author tim
 * @since 2021/3/30
 */
public class NonBlockingNioTest {

    @Test
    public void client(){
        try {
            SocketChannel socketChannel= SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
            //切换为非阻塞
            socketChannel.configureBlocking(false);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
//            buffer.put(new Date().toString().getBytes());
//            buffer.flip();
//            socketChannel.write(buffer);
//            buffer.clear();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String line = scanner.next();
                buffer.put(line.getBytes());
//                buffer.flip();
                buffer.rewind();
                socketChannel.write(buffer);
                buffer.clear();
            }
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void server(){
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //2.切换为非阻塞模式
            serverSocketChannel.configureBlocking(false);
            //3.绑定连接
            serverSocketChannel.bind(new InetSocketAddress(9999));
            Selector selector = Selector.open();
            //将通道注册到选择器上，并指定“监听接收事件”
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            //轮询式的获取选择器上已经准备就绪的事件
            while (selector.select() > 0){
                //获取当前选择器中所有注册的“选择键（已就绪的监听事件）”
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    //判断具体是什么事件
                    if (selectionKey.isAcceptable()){
                        //若接受就绪，获取客户端连接
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        //将该通道设置为非阻塞模式
                        socketChannel.configureBlocking(false);
                        //将该通道注册到选择器上
                        socketChannel.register(selector,SelectionKey.OP_READ);
                    }else if(selectionKey.isReadable()){
                        //获取当前选择器上读就绪的通道
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        //读取数据
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        while ((len = socketChannel.read(buffer)) >0){
                            buffer.flip();
                            System.out.println(new String(buffer.array(),0,len));
                            buffer.clear();
                        }
                    }
                    iterator.remove();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test(){
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String str = scanner.next();
            System.out.println(str);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String str = scanner.next();
            System.out.println(str);
        }
    }
}
